package com.xhwl.centiotdata.suppliersystem.dahuaIcc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.constant.DaHuaIccConstant;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.cent.iot.OrgInfo;
import com.xhwl.common.pojo.cent.sdata.Organization;
import com.xhwl.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author： lixiaoyan
 * @Description：大华icc部门接口对接
 * @Date 2023/2/7 16:05
 */
@Service
public class OrgDaHuaIccHandler {
    private static final Logger log = LoggerFactory.getLogger(OrgDaHuaIccHandler.class);

    @Autowired
    private GeneralDaHuaIccHandler generalDaHuaIccHandler;

    /**
     * 创建组织（对应大华icc的部门）
     *
     * @param configDTO    配置
     * @param organization 组织
     * @return 组织列表
     */
    public String addOrg(PedestrianIntegrationConfigDTO configDTO, Organization organization) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", getDepartmentId(configDTO));
        params.put("name", stringFilter(organization.getName()));
        params.put("parentId", organization.getParentId());
        JSONObject resultObject = generalDaHuaIccHandler.post(DaHuaIccConstant.DEPARTMENT_ADD_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        checkResult(resultObject, DaHuaIccConstant.DEPARTMENT_ADD_URL, params);
        //新增成功数据
        return resultObject.getJSONObject("data").getString("id");
    }

    /**
     *只允许字母和数字 // String regEx ="[^a-zA-Z0-9]";
     *清除掉所有特殊字符
     * @param str
     * @return
     */
    private String stringFilter(String str) {
        if(StringUtils.isEmpty(str)){
            return "";
        }
        String regEx="[`~!#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public void updateOrg(PedestrianIntegrationConfigDTO configDTO, Organization organization) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", organization.getId());
        params.put("name", stringFilter(organization.getName()));
        params.put("parentId", organization.getParentId());
        generalDaHuaIccHandler.put(DaHuaIccConstant.DEPARTMENT_UPDATE_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
    }

    public void deleteOrg(PedestrianIntegrationConfigDTO configDTO, OrgInfo orgInfo) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", orgInfo.getOrgIndexCode());
        JSONObject resultObject = generalDaHuaIccHandler.delete(DaHuaIccConstant.DEPARTMENT_DELETE_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.info("post path:{};params:{};errMsg:{}", DaHuaIccConstant.DEPARTMENT_DELETE_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
        }
    }

    public String getDepartmentId(PedestrianIntegrationConfigDTO configDTO) {
        HashMap<String, Object> params = new HashMap<>(1);
        JSONObject resultObject = generalDaHuaIccHandler.get(DaHuaIccConstant.DEPARTMENT_GENERATE_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        checkResult(resultObject, DaHuaIccConstant.DEPARTMENT_GENERATE_URL, params);
        return resultObject.getJSONObject("data").getString("id");
    }

    public void checkResult(JSONObject resultObject, String url, Map<String, Object> params) {
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", url, JSON.toJSONString(params), resultObject.getString("errMsg"));
            throw new BusinessException(resultObject.getString("errMsg"));
        }
    }

}
